//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using ResourceLabel = CommunityServer.ControlPanel.Controls.ResourceLabel;
using ResourceLinkButton = CommunityServer.ControlPanel.Controls.ResourceLinkButton;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.Membership
{

	/// <summary>
	///		Summary description for CreateEditRole.
	/// </summary>
	public class CreateEditRole : BaseMembershipControl
	{
		
		#region Members

		protected Literal RoleID;
		protected TextBox Name;
		protected TextBox Description;
		protected ResourceLinkButton SaveButton;
		protected ResourceLinkButton DeleteButton;
		protected RoleIcons RoleIcon;
		protected ResourceLabel RoleIconResourceLabel;
		protected ResourceLabel IDResourceLabel;
		protected ResourceLabel DescResourceLabel;
		protected Literal Title;
		protected HtmlInputFile RoleImageUpload;
		protected ResourceLinkButton DeleteImageButton;

		Guid _roleID;

		private bool _isEdit = false;
		protected virtual Boolean IsEdit 
		{
			get 
			{
				return _isEdit;
			}
			set 
			{
				_isEdit = value;
			}
		}

		#endregion

		#region Events

		public event EventHandler RoleSaved;

		protected virtual void OnRoleSaved(EventArgs e)
		{
			RoleSaved(this, e);
		}

		#endregion

		override protected void OnInit(EventArgs e)
		{
			this.Load += new EventHandler(this.Page_Load);
			this.SaveButton.Click +=new EventHandler(SaveButton_Click);
			this.DeleteButton.Click +=new EventHandler(DeleteButton_Click);
			this.DeleteImageButton.Click +=new EventHandler(DeleteImageButton_Click);
			DeleteButton.Attributes["onclick"] = string.Format("return confirm('{0}');", Components.ResourceManager.GetString("CP_Membership_RoleEdit_DeleteConfirmation").Replace("'", @"\'") );

			base.OnInit(e);
		}	

		private void Page_Load(object sender, EventArgs e)
		{

			CSContext context = CSContext.Current;
			_roleID = context.GetGuidFromQueryString("RoleID");

			if (_roleID != Guid.Empty)
				this._isEdit = true;

			RoleIcon.Visible = _isEdit;
			RoleIconResourceLabel.Visible = _isEdit;
			IDResourceLabel.Visible = _isEdit;
			RoleID.Visible = _isEdit;

			if(!Page.IsPostBack)
			{
				Bind();
			}
		}

		protected void Bind() 
		{
			
			if (this._isEdit)
			{
				Role roleToEdit = CommunityServer.Components.Roles.GetRole( _roleID, false );

				if ( roleToEdit != null ) 
				{
					RoleID.Text = roleToEdit.RoleID.ToString();
					Name.Text = roleToEdit.Name;
					Description.Text = roleToEdit.Description;
					RoleIcon.RoleID = roleToEdit.RoleID.ToString();
					Title.Text = string.Format(Components.ResourceManager.GetString("CP_Membership_RoleEdit_Title_Edit"), roleToEdit.Name);

				}

				Description.Enabled = IsRoleEditable( roleToEdit );
				Name.Enabled = IsRoleEditable( roleToEdit );
				SaveButton.Enabled = true;
				DeleteButton.Enabled = IsRoleEditable( roleToEdit );
				DeleteButton.Visible = true;
			}
			else
			{
				Title.Text = ResourceManager.GetString("CP_Membership_RoleEdit_Title_Add");
				DeleteButton.Visible = false;
			}

		
		}

		protected Boolean IsRoleEditable( Role role ) 
		{
			return !CommunityServer.Components.Roles.IsBuiltInRole(role.Name);
		}


		#region Command Handlers

		private void SaveButton_Click(object sender, EventArgs e) 
		{
			
			Role roleToEdit;
			if (!this._isEdit)
			{
				CommunityServer.Components.Roles.AddRole( Name.Text );
				roleToEdit = CommunityServer.Components.Roles.GetRole(Name.Text);
			}
			else
			{
				roleToEdit = CommunityServer.Components.Roles.GetRole( new Guid( RoleID.Text ) );
			}

			if ( IsRoleEditable(roleToEdit) ) 
				UpdateRole( roleToEdit );

			RoleIcon.RoleID = roleToEdit.RoleID.ToString();
			UpdateImage( RoleImageUpload.PostedFile );
			OnRoleSaved(null);
		}

		private void DeleteButton_Click(object sender, EventArgs e) 
		{

			Role role = CommunityServer.Components.Roles.GetRole( new Guid( RoleID.Text ) );
			if ( IsRoleEditable( role ) ) 
			{
				DeleteRole( role );
				RoleIcon.RoleID = role.RoleID.ToString();
				OnRoleSaved(null);
			} 
			else 
			{
				throw new CSException(CSExceptionType.RoleOperationUnavailable);
			}

		}

		public void DeleteImageButton_Click(Object sender, EventArgs e) 
		{
			
			try 
			{
				DeleteImages();
			} 
			catch 
			{
				throw new CSException(CSExceptionType.UnknownError);
			}

			SaveButton_Click( sender, e );
		}

		#endregion


		#region Command Implementations

		protected virtual void UpdateRole( Role role ) 
		{
			role.Name = Name.Text;
			role.Description = Description.Text;
			CommunityServer.Components.Roles.UpdateRole( role );
		}

		protected virtual void DeleteRole( Role role ) 
		{
			CommunityServer.Components.Roles.DeleteRole( role );
        
            // Clear RoleImage cache
            string cacheKey = string.Format("RoleImage-Role:{0}-Site:{1}", _roleID.ToString(), CSContext.Current.SettingsID);
            CSCache.Remove(cacheKey);
        }

		private void UpdateImage (HttpPostedFile postedFile) 
		{
			// validate stream
			if (postedFile.ContentLength <= 0)
				return;

			// Remove any existing images, as this one may have a different extension
			DeleteImages();

			// Get extension if one exists
			string ext = ".";
			if (postedFile.FileName.IndexOf('.') != -1)
				ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("."));
			// If the extension is not .jpg or .png, then default to .gif
			if ( (string.Compare(ext, ".jpg", true) != 0) && (string.Compare(ext, ".png", true) != 0))
				ext = ".gif";

			string imagePath = CSContext.Current.MapPath( String.Format("{0}/utility/roleicons/{1}{2}", Globals.ApplicationPath, _roleID, ext) );
			postedFile.SaveAs(imagePath);

		}

		private void DeleteImages()
		{

			string imagePath = CSContext.Current.MapPath( String.Format("{0}/utility/roleicons/{1}", Globals.ApplicationPath, _roleID) ) + ".{0}";

			// Delete any images with this Role ID
			string vpath = string.Format( imagePath, "gif" );
			if( File.Exists(vpath) )
				File.Delete(vpath);

			vpath = string.Format( imagePath, "jpg" );
			if( File.Exists(vpath) )
				File.Delete(vpath);

			vpath = string.Format( imagePath, "png" );
			if( File.Exists(vpath) )
				File.Delete(vpath);

			// Clear RoleImage cache
            string cacheKey = string.Format("RoleImage-Role:{0}-Site:{1}", _roleID.ToString(), CSContext.Current.SettingsID);
            CSCache.Remove(cacheKey);

		}

		#endregion


	}
}
